<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="规则" prop="soRule">
        <el-input v-model="queryParams.soRule" placeholder="请输入规则名" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['routine:solt:add']">新增规则</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['routine:solt:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['routine:solt:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['routine:solt:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="soltList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="id" />
      <el-table-column label="功能房规则类型" align="center" prop="soRule" />
      <el-table-column label="星期" align="center" prop="roWeekday" />
      <el-table-column label="当前时间段" align="center" prop="roWeektime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['routine:solt:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['routine:solt:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 修改功能房开放时间段对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="规则类型" prop="soRule">
          <el-input v-model="form.soRule" placeholder="请输入规则类型" />
        </el-form-item>
        <el-form-item label="星期" prop="roWeekday">
          <el-input v-model="form.roWeekday" placeholder="请设置星期几" />
        </el-form-item>
        <el-form-item label="设置时间段">
          <div style="display: flex; justify-content: space-between">
            <el-time-select placeholder="起始时间" v-model="form.roStartTime" :picker-options="{
      start: '07:30',
      step: '00:15',
      end: '24:00'
    }">
            </el-time-select>
            <el-time-select placeholder="结束时间" v-model="form.roEndTime" :picker-options="{
      start: '07:30',
      step: '00:15',
      end: '24:30',
      minTime: form.roStartTime
    }">
            </el-time-select>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 新增弹出框 -->

    <el-dialog width="40%" title="设置使用规则" :visible.sync="addVisible" whidth="1000px" append-to-body
      style="position: absolute; top: 100px;">
      <div style="margin-left: 32px;"><label>设置预约规则</label></div>
      <el-dialog width="40%" title="设置使用时间" :visible.sync="innerVisible" append-to-body
        style="position: absolute; top: 100px;">
        <div style="display: flex; margin-bottom: 20px;">
          <label style="margin-right: 20px;margin-top: 10px;">开始时间</label>
          <el-time-select v-model="startTimeValue" :picker-options="startTimeOptions" placeholder="选择时间">
          </el-time-select>
        </div>
        <div style="display: flex;">
          <label style="margin-right: 20px;margin-top: 10px;">结束时间</label>
          <el-time-select v-model="endTimeValue" :picker-options="endTimeOptions" placeholder="选择时间">
          </el-time-select>
        </div>
        <div style="position: absolute; bottom: 20px; right: 10px;">
          <el-button @click="cancelTime" style="margin-right: 10px;">取 消</el-button>
          <el-button style="margin-right: 10px;" @click="addTimeSlot">确定</el-button>
        </div>
      </el-dialog>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <div style="margin-top: 20px;">
          <el-form-item label="规则名字">
            <el-input v-model="SoRule" placeholder="请输入规则名字" style="width: 200px" />
          </el-form-item>
        </div>
        <div style=" display: flex; align-items: center; height:30px ; margin-top: 20px; ">
          <div style="margin-top: 8px;"> <el-form-item label="使用日期"></el-form-item></div>
          <div>
            <el-tabs v-model="activeName" @tab-click="handleClick">
              <el-tab-pane v-for="(day, index) in weekdayslist" :key="index" :name="day.roWeekday"
                :label="day.roWeekday"></el-tab-pane>
            </el-tabs>
          </div>
        </div>
        <div style="display:  flex;align-items: center; position: relative; margin-bottom:20px ; ">
          <div><el-form-item label="使用时间"></el-form-item> </div>
          <div style="display: flex; flex-direction: column; padding-bottom: 10px;">
            <div v-for="(item, indextime) in weekdayslist" :key="indextime"
              style="display: flex; align-items: center; margin-bottom: 12px;" v-if="item.roWeekday === activeName">
              <div>
                <div v-for="(timeSlot, slotIndex) in item.timeSolts"
                  style="display: flex; align-items: center; font-weight: bold;">
                  <div>{{ timeSlot.roStartTime }}-{{ timeSlot.roEndTime }}</div>
                  <div @click="deleteDate(indextime, slotIndex)" style="cursor: pointer; margin-left: 20px;">删除</div>
                </div>
              </div>
            </div>
          </div>
          <div style="position: absolute; left: 350px; top: 8.5px; font-weight: bold;  cursor: pointer;"
            @click="openTime">
            新增
          </div>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitRuleForm">确 定</el-button>
        <el-button @click="cancelRule">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSolt, getSolt, delSolt, addSolt, updateSolt, listSoltRule, InsertAll } from "@/api/routine/solt";

export default {
  name: "Solt",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 功能房开放时间段表格数据
      soltList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        roType: null,
        roWeekday: null,
        soNo: null,
        roWeek: null,
        roWeektime: null,
        soRule: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {

      },
      addVisible: false,
      innerVisible: false,
      weekdayslist: [
        { roWeekday: '星期一', timeSolts: [] },
        { roWeekday: '星期二', timeSolts: [] },
        { roWeekday: '星期三', timeSolts: [] },
        { roWeekday: '星期四', timeSolts: [] },
        { roWeekday: '星期五', timeSolts: [] },
        { roWeekday: '星期六', timeSolts: [] },
        { roWeekday: '星期天', timeSolts: [] }
      ],
      activeName: '星期一', // 默认激活的标签页
      startTimeValue: '',
      endTimeValue: '',
      SoRule: '',
      startTimeOptions: {
        start: '08:30',
        step: '00:15',
        end: '24:00'
      },
      endTimeOptions: {
        start: '08:30',
        step: '00:15',
        end: '24:00'
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询功能房开放时间段列表 */
    getList() {
      this.loading = true;
      listSolt(this.queryParams).then(response => {
        this.soltList = response.rows.map(item => {
          return {
            id: item.id,
            roType: item.roType,
            soRule: item.soRule,
            roWeekday: item.roWeekday,
            soNo: item.soNo,
            roWeek: item.roWeek,
            roWeektime: `${item.roStartTime} - ${item.roEndTime}`
          }
        });
        console.log(this.soltList);
        this.total = response.total;
        this.loading = false;
      })

    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        roType: null,
        roWeekday: null,
        soNo: null,
        roWeek: null,
        roWeektime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.addVisible = true;
      this.title = "添加功能房开放时间段";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.getListSoltRule(row)
      this.reset();
      this.loading = true;
      const id = row.id || this.ids;
      getSolt(id).then(response => {
        const data = response.data;
        const roWeektime = `${data.roStartTime} - ${data.roEndTime}`;
        // 创建新的对象，包含 rtYuyue
        this.form = {
          ...data,
          roWeektime: roWeektime,
          timeRange: [data.roStartTime, data.roEndTime]
        };
        console.log(this.form);
        this.open = true;
        this.title = "修改功能房开放时间段";
        this.loading = false;
      })
    }
    ,
    // 获取选定的规则全部数据
    getListSoltRule(row) {
      // this.queryParams.pageSize = 10000;
      listSoltRule(this.queryParams.pageSize).then(response => {
        console.log(response);
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateSolt(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSolt(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除功能房开放时间段编号为"' + ids + '"的数据项？').then(function () {
        return delSolt(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('routine/solt/export', {
        ...this.queryParams
      }, `solt_${new Date().getTime()}.xlsx`)
    },
    openTime() {
      this.innerVisible = true;
    },
    //添加规则到时间段到星期
    addTimeSlot() {
      const selectedDay = this.weekdayslist.find(day => day.roWeekday === this.activeName);

      if (selectedDay) {
        const roStartTime = this.startTimeValue;
        const roEndTime = this.endTimeValue;

        if (!roStartTime || !roEndTime) {
          this.$message.error('请选择完整的时间段');
          return;
        }

        if (new Date(`1970-01-01 ${roStartTime}`) >= new Date(`1970-01-01 ${roEndTime}`)) {
          this.$message.error('结束时间必须晚于开始时间');
          return;
        }

        const isOverlap = selectedDay.timeSolts.some(slot =>
          (new Date(`1970-01-01 ${roStartTime}`) < new Date(`1970-01-01 ${slot.roEndTime}`)) &&
          (new Date(`1970-01-01 ${roEndTime}`) > new Date(`1970-01-01 ${slot.startroStartTimeTime}`))
        );

        if (isOverlap) {
          this.$message.error('时间段与已有时间段重叠');
          return;
        }

        selectedDay.timeSolts.push({
          roStartTime: roStartTime,
          roEndTime: roEndTime
        });

        this.startTimeValue = '';
        this.endTimeValue = '';
        console.log(this.weekdayslist);
        this.innerVisible = false;
      }
    },    // 删除时间段
    deleteDate(dayIndex, slotIndex) {
      this.weekdayslist[dayIndex].timeSolts.splice(slotIndex, 1);
    },
    //选中的星期
    handleClick(tab) {
      this.activeName = tab.name;
      console.log(this.activeName)
    },
    //关闭内层弹出框
    cancelTime() {
      this.innerVisible = false;
    },
    //关闭新增弹出框
    cancelRule() {
      this.addVisible = false;
    },
    //提交规则
    submitRuleForm() {
      // 构建要提交的数据对象
      const submitData = this.weekdayslist.map(day => ({
        ...day, // 保留原有的属性
        soRule: this.SoRule // 添加 ruleName 属性
      }));
      console.log(submitData);
      InsertAll(submitData).then(response => {
        this.$modal.msgSuccess("规则保存成功");
        this.addVisible = false; 
      }).catch(error => {
        this.$modal.msgError("保存规则失败");
        console.error(error);
      });
    }
  }
};
</script>
<style scoped>
/* 去掉长分割线 */
::v-deep .el-tabs__nav-wrap::after {
  position: static !important;
}

/* 去掉下划线 */
::v-deep .el-tabs__active-bar {
  background-color: transparent !important;
}

/* //选中 */
::v-deep .el-tabs__item.is-active {
  color: rgb(70, 220, 146);
  opacity: 1;
}

/* //悬浮 */
::v-deep .el-tabs__item:hover {
  color: black;
  cursor: pointer;
  opacity: 1;
}
</style>
